package xyz.syyrjx.response;

import xyz.syyrjx.code.SyyrjxRpcCoder;
import xyz.syyrjx.exception.SyyrjxRpcRegistryException;
import xyz.syyrjx.exception.SyyrjxRpcRemoteException;

import java.io.Serializable;
import java.util.Arrays;

/**
 * rpc相应类
 *
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/5 - 17:36
 */
public class SyyrjxRpcResponse<T> implements Serializable {
    private boolean flag;
    private T data;
    private long futureId;

    public static final boolean SUCCESS = true;
    public static final boolean FAIL = false;

    private SyyrjxRpcResponse(){
    }

    public static <T>  SyyrjxRpcResponse success(T data) {
        SyyrjxRpcResponse response = new SyyrjxRpcResponse();
        response.flag = SUCCESS;
        response.data = data;
        return response;
    }

    public static SyyrjxRpcResponse providerFail(Throwable throwable){
        SyyrjxRpcResponse response = new SyyrjxRpcResponse();
        response.flag = FAIL;
        response.data = throwable;
        return response;
    }

    public static SyyrjxRpcResponse providerFail(String msg){
        SyyrjxRpcResponse response = new SyyrjxRpcResponse();
        response.flag = FAIL;
        response.data = new SyyrjxRpcRemoteException(msg);
        return response;
    }

    public static SyyrjxRpcResponse registryFail(String msg){
        SyyrjxRpcResponse response = new SyyrjxRpcResponse();
        response.flag = FAIL;
        response.data = new SyyrjxRpcRegistryException(msg);
        return response;
    }


    public boolean isFlag() {
        return flag;
    }

    public T getData() {
        return data;
    }

    public long getFutureId() {
        return futureId;
    }

    public void setFutureId(long futureId) {
        this.futureId = futureId;
    }

    public String toSerializableString(){
        return Arrays.toString(SyyrjxRpcCoder.ObjectToString(this)) + System.lineSeparator();
    }

    @Override
    public String toString() {
        return "SyyrjxRpcResponse{" +
                "flag=" + flag +
                ", data=" + data +
                ", futureId=" + futureId +
                '}';
    }
}
